package com.intellif.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * @author by mozping
 * @Classname EchoServerHandler
 * @Description TODO
 * @Date 2019/3/27 20:54
 */
public class EchoServerHandler extends ChannelInboundHandlerAdapter {


    //服务端读取到网络数据后的处理
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        ByteBuf by = (ByteBuf) msg;
        System.out.println("msg的类型:" + msg.getClass());
        System.out.println("Server Accept: " + by.toString(CharsetUtil.UTF_8));
        //ctx.write("你收到了吗".getBytes());
        ctx.write(msg);
        ctx.write(Unpooled.copiedBuffer("你收到了吗？",CharsetUtil.UTF_8));
        ctx.write(Unpooled.copiedBuffer("给你回复信息了哦!",CharsetUtil.UTF_8));
    }

    //服务端读取完成网络数据后的处理
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //刷新全部数据，并且关闭连接
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }

    //发生异常后的处理
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

        cause.printStackTrace();
        ctx.close();
    }
}
